package cn.itcast.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * TODO
 *
 * @Author mr.wu
 * @Date 2025/1/3 15:56
 */
@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求实例
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应实例
        ServerHttpResponse response = exchange.getResponse();
        //3.获取QueryString请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //4.获取authorizotion参数
        String first = queryParams.getFirst("authorizotion");
        //5.判断参数值如果不是admin，则响应403
        if (!"admin".equals(first)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        //6.如果是admin，则放行到下一个过滤器
        return chain.filter(exchange);
    }
}
